<template>
  <div class="main">
    <p class="main_text">岗位设置</p>
    <!-- #####################################头部##################################### -->
    <div class="main_nav p20 mb20">
      <el-form :model="searchData" class="df">
        <el-form-item label="部门名称：" class="mr20" style="width: 20%">
          <el-tree-select v-model="searchData.node" :data="sectionData" check-strictly :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="岗位名称：" class="mr20" style="width: 20%">
          <el-input v-model="searchData.name" placeholder="岗位名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchDataBtn">查询</el-button>
          <el-button type="primary" plain @click="resc">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- #####################################底部##################################### -->
    <div class="cyr-flex">
      <div class="mb20">
        <el-button type="primary" @click="centerDialogVisible = true" v-if="roleList.write">添加岗位</el-button>
      </div>
      <div class="cyr-flex-box">
      <!-- <el-table @selection-change="handleSelectionChange" :data="tableData" max-height="400" style="width: 100%" -->
      <el-table :data="tableData"  :header-cell-style="{ background: '#f0f6fe' }"
        :show-overflow-tooltip="true" v-adaptive border>
        <!-- <el-table-column type="selection" width="50" /> -->
        <el-table-column label="ID" prop="id" />
        <el-table-column label="部门" prop="deptName" />
        <el-table-column label="岗位" prop="name" />
        <!-- <el-table-column label="性质" prop="nature" /> -->
        <el-table-column label="状态">
          <template #default="props">
            <el-tag v-if="props.row.state == 'N'" size="small" type="success">启用</el-tag>
            <el-tag v-else size="small" type="info">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="功能集合" prop="roleNames" />
        <!-- <el-table-column label="备注" prop="remarks" /> -->
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="props">
            <!-- <el-button link type="primary" size="small" @click="check(props.row)">绑定角色</el-button> -->
            <el-button link type="primary" size="small" @click="editBtn(props.row)" v-if="roleList.write">
              编辑</el-button>
            <!-- <el-button link type="danger" v-if="props.row.state == 'N'" size="small"
                            @click="stoop(props.row)">停用</el-button>
                        <el-button link type="success" v-if="props.row.state == 'D'" size="small"
                            @click="start(props.row)">启用</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
        @change="handleCurrentChange" />
      </div>
      <!-- 蒙层-----添加岗位 -->
      <el-dialog v-model="centerDialogVisible" align-center width="40%" @close="addDialog">
        <template #header>
          <div class="df aic">
            <el-icon style="color: #fff" size="20">
              <Edit />
            </el-icon>&nbsp;
            <p style="color: #fff">添加岗位</p>
          </div>
        </template>
        <el-form :model="formAdd" label-width="6.25rem" label-position="left" class="df fdc aic">
          <el-form-item label="部门名称：" style="width: 60%">
            <el-tree-select v-model="formAdd.node" :data="sectionData" check-strictly :render-after-expand="false" />
          </el-form-item>
          <el-form-item label="岗位名称：" style="width: 60%">
            <el-input v-model="formAdd.name" placeholder="岗位名称" />
          </el-form-item>
          <el-form-item label="状态：" style="width: 60%">
            <el-select v-model="formAdd.state" placeholder="状态">
              <!-- 启用---N     停用---D -->
              <el-option label="启用" value="N" />
              <el-option label="停用" value="D" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button size="small" @click="centerDialogVisible = false">取消</el-button>
            <el-button size="small" type="primary" @click="AddPosition" v-if="roleList.write">
              添加
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 蒙层-----编辑岗位 -->
      <el-dialog v-model="editDialogVisible" align-center width="40%" @close="editDialog">
        <template #header>
          <div class="df aic">
            <el-icon style="color: #fff" size="20">
              <Edit />
            </el-icon>&nbsp;
            <p style="color: #fff">编辑岗位</p>
          </div>
        </template>
        <el-form :model="editForm" label-width="7.5rem" label-position="left" class="df fdc aic">
          <el-form-item label="部门名称：" style="width: 60%">
            <el-tree-select v-model="editForm.node" :data="sectionData" check-strictly :render-after-expand="false"
              disabled />
          </el-form-item>
          <el-form-item label="岗位名称：" style="width: 60%">
            <el-input v-model="editForm.name" placeholder="岗位名称" />
          </el-form-item>
          <el-form-item label="状态：" style="width: 60%">
            <el-select v-model="editForm.state" placeholder="状态">
              <!-- 启用---N     停用---D -->
              <el-option label="启用" value="N" />
              <el-option label="停用" value="D" />
            </el-select>
          </el-form-item>
          <el-form-item label="关联功能信息：" style="width: 60%">
            <el-select v-model="sysRoleIdArr" style="width: 100%" filterable multiple @change="changeSys">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!--  <el-form-item label="备注：" style="width: 60%;">
                  <el-input v-model="editForm.remarks" type="textarea" />
                </el-form-item> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button size="small" @click="editDialogVisible = false">取消</el-button>
            <el-button size="small" type="primary" @click="editSaveBtn" v-if="roleList.write">
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Edit } from "@element-plus/icons-vue";
import {
  RequestNodeList,
  RequestsysStationDel,
  RequestsysStationGetlistlimit,
  RequestsysStationSave,
  RequestsysStationGetRoleByStation,
  RequestsysRoleGetRole,
  RequestsysStationRoleDispatchSave,
  RequestSysStationRoleDispatchDelete,
  RequestNodeGetDeptTree,
  RequestSysStationGetFunctionByStation,
  RequestEmployeeGetFunctionAuthorize,
} from "../../../api/path/index.js";
import { ElMessage } from "element-plus";
/*------------------------------------- 按钮权限 -------------------------------------*/
import { useRouter } from "vue-router";
import useAuthorize from "@/hooks/authorize";
let roleList = useAuthorize()
// const authorizeFlag = ref<any>();
// const btnAuthority = () => {
//   // console.log(' useRouter()', useRouter().currentRoute.value.meta.title);
//   RequestEmployeeGetFunctionAuthorize(
//     useRouter().currentRoute.value.meta.title
//   ).then((res: any) => {
//     // console.log(res.resultObj);
//     if (res.resultObj == "W") {
//       authorizeFlag.value = false;
//     } else {
//       authorizeFlag.value = true;
//     }
//   });
// };
// btnAuthority();
/*------------------------------------- 按钮权限 -------------------------------------*/
/* 蒙层 */
const centerDialogVisible = ref(false);
const editDialogVisible = ref(false);
const searchData = ref<any>({
  node: "",
  name: "",
});
const searchDataBtn = () => {
  getData();
};

const formAdd = ref({
  name: "",
  node: "",
  status: "",
  state: "",
  visibility: "V",
  kind: "",
  remarks: "",
});
const tableData = ref<any>();
const flag = ref<boolean>(false);
/* 查看 */
const checkTableData = ref<any>([]);
/* 递归 */
let recursionSectionArr = (arr: any) => {
  arr.forEach((item: any) => {
    item.value = item.id;
    item.label = item.name;
    if (item.type == "COMPANY") {
      item.company = item.name;
      if (item.children != null) {
        recursionSectionArr(item.children);
      } else {
        return item;
      }
    } else {
      item.sectionName = item.name;
      if (item.children != null) {
        recursionSectionArr(item.children);
      } else {
        return item;
      }
    }
  });
};
/* 获取部门树 */
const sectionData = ref<any>([]);
RequestNodeGetDeptTree(
  JSON.parse(localStorage.getItem("roleInfo")!).company
).then((res: any) => {
  recursionSectionArr(res.resultObj);
  sectionData.value = res.resultObj;
});
/* 查看&修改 */
const options = ref<any>([]);
/*  重置 */
const resc = () => {
  (searchData.value.node = ""), (searchData.value.name = ""),
  currentPage.value = 1;
  getData();
};
/* ****************************************************************** 获取岗位列表信息 *******************************************************************/
const total = ref<any>(10);
const currentPage = ref(1);
const pageSize = ref(10);
const getData = () => {
  RequestsysStationGetlistlimit({
    page: currentPage.value,
    rows: pageSize.value,
    node: searchData.value.node,
    name: searchData.value.name,
  }).then((res: any) => {
    res.resultObj.data.forEach((item: any) => {
      item.roleNames = item.roleNames.join(",");
    });
    tableData.value = res.resultObj.data;
    total.value = res.resultObj.total;
  });
};
const handleSizeChange = (val: number) => {
  getData();
};
const handleCurrentChange = (val: number) => {
  getData();
};
getData();
/* ****************************************************************** 添加岗位 *******************************************************************/
const addDialog = () => {
  (formAdd.value.name = ""),
    (formAdd.value.node = ""),
    (formAdd.value.state = ""),
    (formAdd.value.remarks = ""),
    (formAdd.value.visibility = ""),
    getData();
};
const AddPosition = () => {
  RequestsysStationSave({
    name: formAdd.value.name,
    node: formAdd.value.node,
    state: formAdd.value.state,
    remarks: formAdd.value.remarks,
    visibility: formAdd.value.visibility,
  }).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      centerDialogVisible.value = false;
      getData();
    } else {
      ElMessage.error(res.msg);
      getData();
    }
  });
};
/* 启用 */
const start = (row: any) => {
  RequestsysStationSave({
    id: row.id,
    state: "N",
  }).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      getData();
    }
  });
};
/* ****************************************************************** 删除单个岗位 *******************************************************************/
const DelSection = (id: any) => {
  RequestsysStationDel(id).then((res: any) => {
    ElMessage.success(res.msg);
    getData();
  });
};
/* ****************************************************************** 获取部门列表 *******************************************************************/
const positionList = ref<any>([]);
const getPostionList = () => {
  RequestNodeList().then((res: any) => {
    positionList.value = res.resultObj;
  });
};
getPostionList();
/* ****************************************************************** 编辑岗位 *******************************************************************/
const editForm = ref<any>({});
const sysRoleIdArr = ref<any>([]);
const editBtn = (row: any) => {
  /* 获取角色信息 */
  //   RequestSysStationGetFunctionByStation(row.id).then((res: any) => {
  //     console.log(res);
  //   });
  RequestsysRoleGetRole({
    company: JSON.parse(localStorage.getItem("roleInfo")!).company,
  }).then((res: any) => {
    res.resultObj.forEach((item: any) => {
      options.value.push({
        value: item.id + "",
        label: item.name,
      });
    });
  });
  RequestsysStationGetRoleByStation(row.id).then((res: any) => {
    // console.log("res.resultObj", res.resultObj);
    res.resultObj.forEach((item: any) => {
      sysRoleIdArr.value.push({
        value: item.id + "",
        label: item.name,
      });
    });
  });
  console.log(row);
  editForm.value = row;
  editDialogVisible.value = true;
};
const newCheckTableData = ref<any>([]);
const newCheckTableIdArr = ref<any>([]);
const changeSys = (event: any) => {
  newCheckTableIdArr.value = event;
  console.log("event", event);
  //   console.log("sysRoleIdArr", sysRoleIdArr.value);
};
const editDialog = () => {
  newCheckTableData.value = [];
  options.value = [];
  sysRoleIdArr.value = [];
};
const editSaveBtn = () => {
  console.log(sysRoleIdArr.value);
  console.log(editForm.value);
  newCheckTableIdArr.value.forEach((item: any) => {
    if (item.value) {
      newCheckTableData.value.push({
        name: "",
        sysRoleId: item.value,
        bindNode: "",
      });
    } else {
      newCheckTableData.value.push({
        name: "",
        sysRoleId: item,
        bindNode: "",
      });
    }
  });
  console.log("editForm.value", editForm.value);
  RequestsysStationSave(editForm.value).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      editDialogVisible.value = false;
      getData();
    } else {
      ElMessage.error(res.msg);
      getData();
    }
  });

  const blob = new Blob([JSON.stringify(newCheckTableData.value)], {
    type: "application/json;charset=utf-8",
  });
  const blob2 = new Blob([JSON.stringify(editForm.value.id)], {
    type: "application/json;charset=utf-8",
  });
  let save = new FormData();
  save.append("sys_role", blob);
  save.append("sys_station_id", blob2);
  flag.value = false;
  RequestsysStationRoleDispatchSave(save).then((res: any) => {
    console.log(res);
    if (res.success == true) {
      newCheckTableData.value = [];
    }
  });
};
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .main_nav {
    border-radius: 6px;
    background-color: #fff;
    .el-form-item{
      margin-bottom: 0;
    }
  }

  .main_content {
    background-color: #fff;
  }
}

.addTable {
  width: 100%;
  text-align: center;
  height: 2.5rem;
  line-height: 2.5rem;
  background-color: #e7f0fe;
  border: 0.0625rem dotted #116cf8;
  margin-top: 0.375rem;
  color: #116cf8;
  user-select: none;
  cursor: pointer;
}

.el-select,
.el-input {
  width: 100%;
}

/* 弹出框样式 */
::v-deep .el-dialog__header {
  background-color: #116cf8;
  margin-right: 0;

  .el-icon svg {
    color: #fff;
  }
}

::v-deep .el-dialog__title {
  color: #fff;
}

</style>
